//获取用户信息,更新用户信息 更换头像 重置密码

const db = require('../db');

const express = require('express');
const router = express.Router();

const { md5 } = require('utility');

// ----------------------------获取用户信息-----------------------
router.get('/userinfo', (req, res) => {
    //根据接口看到数据通过数据拿,调用我们封装好的db
    /* tip:只能有一个res.send() */
    /* 1.获取某个用户信息通过id来识别 
        2.登陆页面登陆完就会创建token,id就保存在token中
        3.我们在前端连接接口,在请求头中就会携带Authorization:token
        4.token又是经过加密的字符串,所以我们就要解密token获取用户id
        5.我们可以通过jsonwebtoken解锁,问题是在哪里开始解密,
        6.以my开头的接口地址都需要携带token,因为在个人中心接口和文章相关接口需要token认证,所以在入口文件index.js解密token
    */
    //console.log(req.user);
    let sql = `select * from user where id=${req.user.id}`
    db(sql, (err, result) => {
        if (err) throw err;
        res.send({ status: 0, message: '获取用户信息成功', data: result[0] })
    })
})

//---------更换头像------------
router.post('/avatar', (req, res) => {
    let avatar = req.body.avatar;
    //console.log(req.body.avatar);
    db(`update user set user_pic='${avatar}' where id=${req.user.id}`, (err, result) => {
        if (err) throw err;
        res.send({ status: 0, message: '更新成功' })
    })
});

//------------------------------更新用户信息接口---------------------------
router.post('/userinfo', (req, res) => {
    //模拟接口才用  
    // let { id, nickname, email } = req.body;
    // if (id != req.user.id) return res, send({ status: 1, message: '无权更新' });
    //  let sql = `update user set nickname='${nickname}',email='${email}' where id =${id}` 
    let {nickname, email } = req.body;
    let sql = `update user set nickname='${nickname}',email='${email}' where id =${req.user.id}`
    db(sql, (err, result) => {
        if (err) throw err;
        res.send({ status: 0, message: '更新用户信息成功' });
    })

})

//------------------------------更新用户密码--------------------------
router.post('/updatepwd', (req, res) => {
    let {oldPwd, newPwd, } = req.body;
    oldPwd = md5(oldPwd);
    newPwd = md5(newPwd);
    let sql = `select * from user where id=${req.user.id}`
    db(sql, (err, result) => {
        if (err) throw err;
        if (result[0].password === newPwd) {
            res.send({ status: 1, message: '新密码不能和旧密码一致' })
        } else if (result[0].password === oldPwd) {
            db(`update user set password='${newPwd}' where id =${req.user.id}`, (e, r) => {
                if (e) throw e;
                res.send({ status: 0, message: '更新密码成功' })
            })
        } else {
            res.send({ status: 1, message: '原密码错误' })
        }
    })
})






module.exports = router;